package org.lionel.task;

import java.util.Map;
import java.util.concurrent.DelayQueue;


public class CheckJobProcesser {

    /**
     * 延时队列，存放处理好的工作任务结果
     */
    private static DelayQueue<Item<String>> queue = new DelayQueue<>();

    private static CheckJobProcesser processer = new CheckJobProcesser();

    private CheckJobProcesser() {
    }

    /**
     * 使用单例
     */
    public static CheckJobProcesser getInstance() {
        return processer;
    }

    /**
     * 处理队列中的到期任务
     */
    public static class FetchJob implements Runnable {
        private static DelayQueue<Item<String>> queue = CheckJobProcesser.queue;
        private static Map<String, JobInfo<?>> jobInfoMap = PendingJobPool.getMap();

        @Override
        public void run() {
            while (true) {
                try {
                    // 从延时队列DelayQueue中获取任务
                    Item<String> item = queue.take();
                    String jobName = item.getData();
                    jobInfoMap.remove(jobName);
                    System.out.println(jobName + " 过期了，从缓存中清除");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 任务完成后，放入队列，经过expireTime时间后，从整个框架中移除
     */
    public void putJob(long expireTime, String jobName) {
        Item<String> item = new Item<>(expireTime, jobName);
        queue.offer(item);
        System.out.println(jobName + " 已经放入过期检查缓存，时长：" + expireTime);
    }

    /**
     * 处理过期任务设置为守护线程
     */
    static {
        Thread thread = new Thread(new FetchJob());
        thread.setDaemon(true);
        thread.start();
        System.out.println("开启过期检查的任务线程。。。");
    }

}
